
package com.creditease.tmsp.modules.sys.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import com.creditease.tmsp.common.utils.SpringContextHolder;
import com.creditease.tmsp.modules.sys.dao.SysResourceDao;
import com.creditease.tmsp.modules.sys.dao.SysUserDao;
import com.creditease.tmsp.modules.sys.dao.UserRoleDao;
import com.creditease.tmsp.modules.sys.entity.SysResource;
import com.creditease.tmsp.modules.sys.entity.SysUser;
import com.creditease.tmsp.modules.sys.entity.SysUserRole;
import com.creditease.tmsp.modules.sys.security.SystemAuthorizingRealm.Principal;

/**
 * @Description：用户工具类
 * @author：
 * @CreateDate：
 * @Company:
 * @version V1.0
 */
public class SysUserUtils {

	private static SysUserDao userDao = SpringContextHolder.getBean(SysUserDao.class);
	private static UserRoleDao userRoleDao = SpringContextHolder.getBean(UserRoleDao.class);
	private static SysResourceDao sysResourceDao = SpringContextHolder.getBean(SysResourceDao.class);
	
	public static SysUser getUser(boolean... isRefresh){
		SysUser user = null;

			try{
				Subject subject = SecurityUtils.getSubject();
				Principal principal = (Principal)subject.getPrincipal();
				if (principal!=null){
					user = userDao.getById(principal.getId());
				}
			}catch (UnavailableSecurityManagerException e) {
				
			}catch (InvalidSessionException e){
				
			}
		return user;
	}
	

	public static List<SysUserRole> getRoleList(){
		SysUser user = getUser();
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("userId", user.getId());
		List<SysUserRole> list = userRoleDao.find(params);

		return list;
	}
	
	public static List<SysResource> getMenuList(){

		List<SysResource> menuList = new ArrayList<SysResource>();

			SysUser user = getUser();
			if (user.isAdmin()){
				menuList = sysResourceDao.findAllSysResource();
			}else{
				List <SysUserRole> list = getRoleList();				
				List<String> roleIdList = new ArrayList<String>();
				for(SysUserRole sur: list){
					roleIdList.add(sur.getRoleId());
				}
				menuList = sysResourceDao.findByRoles(roleIdList);
			}

		return menuList;
	}
	

	public static SysUser getUserById(String id){
		if(StringUtils.isNotBlank(id)) {
			return userDao.getById(id);
		} else {
			return null;
		}
	}
	
	
}
